const fs = require('fs').promises;
const path = require('path');

// 解析Markdown文件，提取标题和内容
function parseMarkdown(content) {
  const lines = content.split('\n');
  const sections = [];
  let currentSection = null;
  let currentContent = [];

  for (let line of lines) {
    if (line.startsWith('#')) {
      // 如果遇到新标题，保存当前段落并创建新段落
      if (currentSection) {
        currentSection.content = currentContent.join('\n');
        sections.push(currentSection);
      }
      const level = line.match(/^#+/)[0].length;
      currentSection = {
        title: line.replace(/^#+\s*/, ''),
        level,
        content: '',
        children: []
      };
      currentContent = [];
    } else {
      currentContent.push(line);
    }
  }

  // 保存最后一个段落
  if (currentSection) {
    currentSection.content = currentContent.join('\n');
    sections.push(currentSection);
  }

  return sections;
}

// 构建父子层级关系
function buildHierarchy(sections) {
  const root = { level: 0, children: [] };
  const stack = [root];

  for (const section of sections) {
    while (stack.length > 1 && stack[stack.length - 1].level >= section.level) {
      stack.pop();
    }
    stack[stack.length - 1].children.push(section);
    stack.push(section);
  }

  return root.children;
}

// 生成父子分段格式的内容
function generateOutput(sections, parentContext = '') {
  let output = '';
  
  for (const section of sections) {
    const currentContext = parentContext + (parentContext ? ' > ' : '') + section.title;
    
    // 添加父块（上下文）
    output += `---\ncontext: ${currentContext}\n---\n`;
    output += section.content.trim() + '\n\n';
    
    // 处理子块
    if (section.children && section.children.length > 0) {
      output += generateOutput(section.children, currentContext);
    }
  }
  
  return output;
}

// 主函数
async function processMarkdownFiles() {
  try {
    // 创建output目录（如果不存在）
    await fs.mkdir('output', { recursive: true });
    
    // 读取files目录下的所有md文件
    const files = await fs.readdir('files');
    const mdFiles = files.filter(file => file.endsWith('.md'));
    
    for (const file of mdFiles) {
      // 读取文件内容
      const content = await fs.readFile(path.join('files', file), 'utf-8');
      
      // 解析并处理内容
      const sections = parseMarkdown(content);
      const hierarchy = buildHierarchy(sections);
      const output = generateOutput(hierarchy);
      
      // 写入转换后的文件
      await fs.writeFile(
        path.join('output', file),
        output,
        'utf-8'
      );
      
      console.log(`Processed ${file} successfully`);
    }
    
    console.log('All files processed successfully');
  } catch (error) {
    console.error('Error processing files:', error);
  }
}

// 运行程序
processMarkdownFiles();